import { Message } from '@arco-design/web-vue';
import { getToken } from '@/utils/auth';
import { getDicts } from '@/api/system/dict-data';

const initFields = async (datas: any, tag = 'a-checkbox-group') => {
  const data: {
    fields?: any;
    data?: any;
    keys?: any;
  } = {
    fields: [],
    data: {},
    keys: [],
  };
  const listP = [];
  for (let i = 0; i < datas.length; i += 1) {
    listP.push(
      new Promise((resolve, reject) => {
        getDicts(datas[i].dictValue)
          .then((res) => {
            resolve({
              ...datas[i],
              ...res,
            });
          })
          .catch((err) => {
            reject(err);
          });
      })
    );
  }
  const res = await Promise.all(listP);
  for (let i = 0; i < res.length; i += 1) {
    const item: any = res[i];
    const keys = item.remark.split('-');
    data.fields = [
      ...data.fields,
      ...[
        {
          key: keys[0],
          label: item.dictLabel,
          tag,
          attrs: {
            placeholder: `请选择${item.dictLabel}`,
            options: item.data.map((d: { dictValue: any; dictLabel: any }) => ({
              ...d,
              value: d.dictValue,
              label: d.dictLabel,
            })),
          },
          decorator: {
            rules: [{ required: false, message: `请选择${item.dictLabel}` }],
          },
          formItemAttrs: {
            'label-col-props': { span: 5 },
            'wrapper-col-props': { span: 19 },
          },
        },
        {
          key: `${keys[1] || `${keys[0]}-other`}`,
          label: `其他病症`,
          tag: 'a-input',
          relation: keys[0],
          attrs: {
            placeholder: `请输入${item.dictLabel}其他病症`,
          },
          decorator: {
            rules: [
              { required: false, message: `请输入${item.dictLabel}其他病症` },
            ],
          },
          formItemAttrs: {
            'label-col-props': { span: 5 },
            'wrapper-col-props': { span: 19 },
          },
          show: (value: any, field: any, fields: any) => {
            const key = field.relation;
            const relation = fields?.find((f: { key: any }) => f.key === key);
            const other = relation?.attrs?.options?.find(
              (op: { label: string }) => op.label === '其他'
            );
            const relationValue = value[key] || [];
            if (relationValue?.includes(other?.dictValue)) {
              return true;
            }
            return false;
          },
        },
      ],
    ];
    data.data[keys[0]] = item.data.map((d: { dictLabel: any }) => {
      return {
        ...d,
        label: `${item.dictLabel}-${d.dictLabel}`,
      };
    });
    data.keys = [...data.keys, keys[0]];
  }
  return data;
};

export default async (options: any, callback: any) => {
  let complications: any = {
    fileds: [],
  };
  let contagions: any = {
    fileds: [],
  };
  const complicaRes = await getDicts(options.complication_type);
  if (complicaRes.code !== 200) {
    Message.error(complicaRes.msg);
  }
  complications = await initFields(complicaRes.data);
  const contagionRes = await getDicts(options.contagion_type);
  if (contagionRes.code !== 200) {
    Message.error(contagionRes.msg);
  }
  contagions = await initFields(contagionRes.data, 'a-radio-group');

  callback({
    searchFileds: [
      {
        span: 5,
        field: 'deptId',
        placeholder: '请输入所属科室',
        label: '所属科室',
        tag: 'a-tree-select',
        initValue: '',
        attrs: {
          'data': options.deptTree,
          'treeProps': {
            virtualListProps: {
              height: 200,
            },
          },
          'field-names': {
            key: 'id',
            title: 'label',
          },
          'allow-search': true,
          'allow-clear': true,
          'filter-tree-node': (
            searchValue: string,
            nodeData: { label: string }
          ) => {
            return (
              String(nodeData.label)
                .toLowerCase()
                .indexOf(String(searchValue).toLowerCase()) > -1
            );
          },
        },
      },
      {
        span: 5,
        field: 'nickName',
        placeholder: '请输入患者姓名',
        label: '患者姓名',
        tag: 'a-input',
        initValue: '',
      },
      {
        span: 5,
        field: 'idNumber',
        placeholder: '请输入身份证号',
        label: '身份证号',
        tag: 'a-input',
        initValue: '',
      },
      {
        span: 5,
        field: 'sex',
        placeholder: '请选择性别',
        label: '性别',
        initValue: '',
        tag: 'a-select',
        attrs: {
          options: options.sys_user_sex,
        },
      },
    ],
    tableColumns: [
      {
        dataIndex: 'id',
        title: '序号',
        width: 150,
      },
      {
        dataIndex: 'nickName',
        title: ' 患者姓名',
        width: 150,
      },
      {
        dataIndex: 'sex',
        title: '患者性别',
        slotName: 'sex',
        width: 100,
      },
      {
        dataIndex: 'idNumber',
        title: '身份证号',
        width: 200,
      },
      {
        dataIndex: 'complication_type',
        title: '合并症',
        slotName: 'complication_type',
        data: complications.data,
        keys: complications.keys,
        width: 200,
      },
      {
        dataIndex: 'contagion_type',
        title: '传染病筛查',
        slotName: 'contagion_type',
        data: contagions.data,
        keys: contagions.keys,
        width: 200,
      },
      {
        dataIndex: 'remark',
        title: '备注',
        ellipsis: true,
        tooltip: true,
      },
      {
        dataIndex: 'createTime',
        title: '检查时间',
      },
      {
        dataIndex: 'optional',
        title: '操作',
        slotName: 'optional',
        width: 220,
      },
    ],
    editFields: [
      {
        key: 'userId',
        label: '患者',
        tag: 'a-select',
        attrs: {
          options: options.userList,
          placeholder: '请选择患者',
          allowSearch: true,
        },
        formItemAttrs: {
          'label-col-props': { span: 5 },
          'wrapper-col-props': { span: 19 },
        },
        decorator: {
          rules: [{ required: true, message: '请选择患者' }],
        },
      },
      {
        slot: 'complication_type',
        formItemAttrs: {
          'label-col-props': { span: 0 },
          'wrapper-col-props': { span: 5 },
        },
      },
      ...(complications?.fields as Array<any>),
      {
        slot: 'contagion_type',
        formItemAttrs: {
          'label-col-props': { span: 0 },
          'wrapper-col-props': { span: 5 },
        },
      },
      ...(contagions?.fields as Array<any>),
      {
        key: 'pictureAddress',
        label: '术后检查信息',
        tag: 'XUpload',
        attrs: {
          config: {
            'list-type': 'picture-card',
            'action': `${import.meta.env.VITE_API_BASE_URL}${import.meta.env.VITE_UPLOAD_URL
              }`,
            'headers': {
              Authorization: `Bearer ${getToken()}`,
            },
            'imagePreview': true,
            'limit': 9,
            'accept': ['image/*'],
          },
        },
        decorator: {
          rules: [
            { required: false, message: '请上传术后检查信息' },
            {
              validator: (value: any, cb: (arg0: string) => void) => {
                const inUpload = value?.find(
                  (item: { status: string }) => item.status !== 'done'
                );
                if (inUpload?.status === 'uploading') {
                  cb('文件上传中！');
                } else if (inUpload?.status === 'error') {
                  cb('文件上传错误，请重试！');
                } else if (inUpload?.status === 'init') {
                  cb('文件未上传！');
                }
              },
            },
          ],
        },
        formItemAttrs: {
          'label-col-props': { span: 5 },
          'wrapper-col-props': { span: 19 },
        },
      },
      {
        key: 'formAddress',
        label: '检查表格',
        tag: 'XUpload',
        attrs: {
          config: {
            action: `${import.meta.env.VITE_API_BASE_URL}${import.meta.env.VITE_UPLOAD_URL
              }`,
            headers: {
              Authorization: `Bearer ${getToken()}`,
            },
          },
        },
        decorator: {
          rules: [
            { required: false, message: '请上传检查表格' },
            {
              validator: (value: any, cb: (arg0: string) => void) => {
                const inUpload = value?.find(
                  (item: { status: string }) => item.status !== 'done'
                );
                if (inUpload?.status === 'uploading') {
                  cb('文件上传中！');
                } else if (inUpload?.status === 'error') {
                  cb('文件上传错误，请重试！');
                } else if (inUpload?.status === 'init') {
                  cb('文件未上传！');
                }
              },
            },
          ],
        },
        formItemAttrs: {
          'label-col-props': { span: 5 },
          'wrapper-col-props': { span: 19 },
        },
      },
      {
        key: 'remark',
        label: '备注',
        tag: 'a-input',
        attrs: {
          placeholder: '请输入备注',
        },
        decorator: {
          rules: [{ required: false, message: '请输入备注' }],
        },
        formItemAttrs: {
          'label-col-props': { span: 5 },
          'wrapper-col-props': { span: 19 },
        },
      },
    ],
  });
};
